-module(sorter).
-export([start/1, stop/1, ascending/2, descending/2]).

%%D:/Danielle/Quarter 3/INF 102/102Workspace/Assignment4

%%Port = open_port({spawn, "/usr/bin/java -cp /Users/danielleyu/School/102Workspace/Assignment4/bin:/Library/Java/JavaVirtualchines/1.7.0.jdk/Contents/Home/jre/lib inf102.java.sorter.Main"},                      [{packet, 1}])

start(JavaLocation) ->
  JavaPortPid = open_port({spawn, JavaLocation}, [{packet, 1}]),
  register(sorterserver, spawn(fun() -> run(JavaPortPid) end)),
  sorterserver ! {self(), start},
  
  receive
    {sorter_server_result, {ok, StartPid}} ->
      {ok, StartPid}
  end.

stop(StartPid) ->
  receive
    {StartPid, {stop}} ->
      StartPid ! stop
  after 5000 ->
    couldnotstop
  end.
  
ascending(StartPid, List) ->
  sorterserver ! {List, self(), ascending}.
  
descending(StartPid, List) ->
  sorterserver ! {List, self(), descending}.
  
run(JavaPortPid) ->
  receive
    {ResponsePid, start} ->
      respond(ResponsePid, {ok, ResponsePid}),
      run(JavaPortPid);
      
    {List, AscendingPid, ascending} ->
      JavaPortPid ! {AscendingPid, {command, [1, List]}},
      run(JavaPortPid);
      
    {List, DescendingPid, descending} ->
      JavaPortPid ! {DescendingPid, {command, [2, List]}},
      run(JavaPortPid)
  end.

%%respond
respond(ResponsePid, Result) ->
	ResponsePid ! {sorter_server_result, Result}.